package org.jeecg.modules.system.service.impl;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.util.SsoUtil;
import org.jeecg.modules.system.entity.SysAnnouncementRead;
import org.jeecg.modules.system.entity.SysAnnouncementSend;
import org.jeecg.modules.system.mapper.SysAnnouncementReadMapper;
import org.jeecg.modules.system.mapper.SysAnnouncementSendMapper;
import org.jeecg.modules.system.model.AnnouncementSendModel;
import org.jeecg.modules.system.service.ISysAnnouncementSendService;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * @Description: 用户通告阅读标记表
 * @Author: jeecg-boot
 * @Date:  2019-02-21
 * @Version: V1.0
 */
@Service
public class SysAnnouncementSendServiceImpl extends ServiceImpl<SysAnnouncementSendMapper, SysAnnouncementSend> implements ISysAnnouncementSendService {

	@Resource
	private SysAnnouncementSendMapper sysAnnouncementSendMapper;
	
	@Resource
	private SysAnnouncementReadMapper sysAnnouncementReadMapper;

	@Override
	public List<String> queryByUserId(String userId) {
		return sysAnnouncementSendMapper.queryByUserId(userId);
	}

	@Override
	public Page<AnnouncementSendModel> getMyAnnouncementSendPage(Page<AnnouncementSendModel> page,
			AnnouncementSendModel announcementSendModel) {
		 return page.setRecords(sysAnnouncementSendMapper.getMyAnnouncementSendList(page, announcementSendModel));
	}

	@Override
	public void updateRead(String anntId, String userId, boolean isPc) {
		SysAnnouncementRead read =  sysAnnouncementReadMapper.findByAnntUserId(anntId,userId);
		if (read == null){ //不存在插入
			read = new SysAnnouncementRead();
			read.setAnntId(anntId);
			read.setUserId(userId);
			if (isPc){
				read.setPcFirstReadIp(SecurityUtils.getSubject().getSession().getHost());
				read.setPcFirstReadTime(new Date());
			} else {
				read.setAppFirstReadIp(SecurityUtils.getSubject().getSession().getHost());
				read.setAppFirstReadTime(new Date());
			}
			sysAnnouncementReadMapper.insert(read);
		} else { //更新
			if (isPc){
				if (read.getPcFirstReadTime() == null){
					read.setPcFirstReadIp(SecurityUtils.getSubject().getSession().getHost());
					read.setPcFirstReadTime(new Date());
				} else {
					read.setPcLastReadIp(SecurityUtils.getSubject().getSession().getHost());
					read.setPcLastReadTime(new Date());
				}
			} else {
				if (read.getAppFirstReadTime() == null){
					read.setAppFirstReadIp(SecurityUtils.getSubject().getSession().getHost());
					read.setAppFirstReadTime(new Date());
				} else {
					read.setAppLastReadIp(SecurityUtils.getSubject().getSession().getHost());
					read.setAppLastReadTime(new Date());
				}
			}
			sysAnnouncementReadMapper.updateRead(read);
		}
	}

}
